<template>
<div class="sub-category">
   <div class="container">
    <!-- 面包屑 -->
       <SubBread></SubBread>
    <!-- 筛选 -->
       <SubFilter @filter-change="changeFilter"></SubFilter>
    <!-- 结果区域 -->
      <div class="goods-list">
      <!-- 排序 -->
         <SubSort @sort-change="sortChange"></SubSort>
      <!-- 列表 -->
          <ul>
              <li v-for="item in goodsList" :key="item.id">
                  <GoodsItem :goods="item"></GoodsItem>
              </li>
          </ul>
      <!-- 加载 -->
          <XtxInfiniteLoading :loading="loading" :finished="finished" @infinite="getData"></XtxInfiniteLoading>
      </div>
   </div>
</div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { getSubCategoryGoods } from '@/api/category'
import SubBread from "@/views/category/components/sub-bread.vue";
import SubFilter from "@/views/category/components/sub-filter.vue";
import SubSort from "@/views/category/components/sub-sort.vue";
import GoodsItem from "@/views/category/components/goods-item.vue";
import XtxInfiniteLoading from "@/components/library/xtx-infinite-loading.vue";

// 1. 基础布局
// 2. 无限加载组件
// 3. 动态加载数据且渲染
// 4. 任何筛选条件变化需要更新列表

onMounted(() => {
    getData()
})

const route = useRoute()
const loading = ref(false)
const finished = ref(false)
const goodsList = ref([])

// 查询参数
let reqParams = {
    page: 1,
    pageSize: 20
}

// 获取数据函数
const getData = async () => {
    loading.value = true
    reqParams.categoryId = route.params.id
    const { result } = await getSubCategoryGoods(reqParams)
    if (result.items.length) {
        goodsList.value.push(...result.items)
        reqParams.page++
    } else {
        // 加载完毕
        finished.value = true
    }
    // 请求结束
    loading.value = false
}

// 切换二级分类重新加载
watch(() => route.params.id, (newVal) => {
    if (newVal && route.path === (`/category/sub/${newVal}`)) {
        goodsList.value = []
        reqParams = {
            page: 1,
            pageSize: 20
        }
        finished.value = false
    }
})

// 1. 更改排序组件的筛选数据，重新请求
const sortChange = (sortParams) => {
    reqParams = { ...reqParams,...sortParams}
    reqParams.page = 1
    goodsList.value = []
    finished.value = false
}

// 2. 更改筛选组件的筛选数据，重新请求
const changeFilter = (filterParams) => {
    reqParams = { ...reqParams,...filterParams}
    reqParams.page = 1
    goodsList.value = []
    finished.value = false
}
</script>

<style scoped lang="less">
.goods-list {
   background-color: #fff;
   padding: 0 25px;
   margin-top: 25px;
  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;
    li {
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>